/** 
 * File-Name:FundRepository.java
 *
 * Created on 2011-6-2 下午09:15:14
 * 
 * @author: Neo (neolimeng@gmail.com)
 * Software Engineering Institute, Peking University, China
 * 
 * Copyright (c) 2009, Peking University
 * 
 *
 */
package xiaoyou.service;

import java.sql.Connection;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.apache.log4j.Logger;

import xiaoyou.dao.FundDao;
import xiaoyou.entity.Fund;
import xiaoyou.neoutil.CommonService;
import xiaoyou.neoutil.DaoSupport;
import xiaoyou.neoutil.Page;

/**
 * Description:
 * 
 * @author: Neo (neolimeng@gmail.com) Software Engineering Institute, Peking
 *          University, China
 * @version 1.0 2011-6-2 下午09:15:14
 */
public class FundRepository extends CommonService {
	private static Logger log = Logger.getLogger(FundRepository.class);
	private String SQL_INSERT = "INSERT INTO fund(uuid, name, donatorName, donatorIntro, donationNum, donationNumFile, foundDate, usageProcedures, organization, fundUsage, authorId, publishDate, updateDate, entityStatus, reserve01, reserve02, reserve03, reserve04, reserve05) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
	private String SQL_UPDATE = "UPDATE fund SET uuid=?, name=?, donatorName=?, donatorIntro=?, donationNum=?, donationNumFile=?, foundDate=?, usageProcedures=?, organization=?, fundUsage=?, authorId=?, updateDate=?, entityStatus=?, reserve01=?, reserve02=?, reserve03=?, reserve04=?, reserve05=? WHERE id=?";
	private String SQL_DELETE_BY_ID = "UPDATE fund SET entityStatus=0 WHERE id=?";
	private String SQL_GET_BY_ID = "SELECT * FROM fund WHERE id=? AND entityStatus=1";
	private String SQL_GET_BY_UUID = "SELECT * FROM fund WHERE uuid=? AND entityStatus=1";
	private String SQL_GET_ALL = "SELECT * FROM fund WHERE entityStatus=1 order by publishDate DESC";
	private String SQL_GET_LATEST_ALL = "SELECT * FROM fund WHERE entityStatus=1 ORDER BY updateDate DESC LIMIT 0,?";

	public int save(Fund fund) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { fund.getUuid(), fund.getName(),
					fund.getDonatorName(), fund.getDonatorIntro(),
					fund.getDonationNum(), fund.getDonationNumFile(),
					fund.getFoundDate(), fund.getUsageProcedures(),
					fund.getOrganization(), fund.getFundUsage(),
					fund.getAuthorId(), new Date(), new Date(), 1,
					fund.getReserve01(), fund.getReserve02(),
					fund.getReserve03(), fund.getReserve04(),
					fund.getReserve05() };
			fundDao.execute(SQL_INSERT, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("保存Fund对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int update(Fund fund) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { fund.getUuid(), fund.getName(),
					fund.getDonatorName(), fund.getDonatorIntro(),
					fund.getDonationNum(), fund.getDonationNumFile(),
					fund.getFoundDate(), fund.getUsageProcedures(),
					fund.getOrganization(), fund.getFundUsage(),
					fund.getAuthorId(), new Date(), fund.getEntityStatus(),
					fund.getReserve01(), fund.getReserve02(),
					fund.getReserve03(), fund.getReserve04(),
					fund.getReserve05(), fund.getId() };
			fundDao.execute(SQL_UPDATE, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("更新Fund对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public int delete(long id) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { id };
			fundDao.execute(SQL_DELETE_BY_ID, params);
			return SUCCESS;
		} catch (Exception e) {
			log.error("假删除Fund对象出现异常！！");
			e.printStackTrace();
			return FAIL;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Fund get(long id) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { id };
			List<Fund> funds = fundDao.find(SQL_GET_BY_ID, params);
			if (funds == null) {
				return null;
			} else if (funds.size() > 1) {
				log.error("根据ID查询到的Fund个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				return funds.get(0);
			}
		} catch (Exception e) {
			log.error("根据ID取得Fund对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Fund get(String uuid) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { uuid };
			List<Fund> funds = fundDao.find(SQL_GET_BY_UUID, params);
			if (funds == null) {
				return null;
			} else if (funds.size() > 1) {
				log.error("根据UUID查询到的Fund个数不唯一，为防止错误，返回null!");
				return null;
			} else {
				Fund fund = funds.get(0);

				UserRepository userRepository = new UserRepository();
				fund.setAuthor(userRepository.get(fund.getAuthorId()));

				return fund;
			}
		} catch (Exception e) {
			log.error("根据UUID取得Fund对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public Page<Fund> getFunds(final Page<Fund> page) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Page<Fund> funds = fundDao.find(page, SQL_GET_ALL);
			return funds;
		} catch (Exception e) {
			log.error("取得所有Fund对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	public List<Fund> getLatestFunds(int topNum) {
		Connection connection = DaoSupport.getConnection();
		FundDao fundDao = new FundDao(connection);

		try {
			Object[] params = { topNum };
			List<Fund> funds = fundDao.find(SQL_GET_LATEST_ALL, params);
			return funds;
		} catch (Exception e) {
			log.error("取得所有Fund对象出现异常！！");
			e.printStackTrace();
			return null;
		} finally {
			try {
				DbUtils.close(connection);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}

	/**
	 * Description:
	 * 
	 * @param args
	 *            void
	 */
	public static void main(String[] args) {
		Fund fund = new Fund();
		fund.setName("专项基金");
		fund.setAuthorId(1L);
		// fund.setId(1L);

		FundRepository fundRepository = new FundRepository();
		fundRepository.save(fund);
		// fundRepository.update(fund);

		List<Fund> funds = fundRepository.getLatestFunds(3);
		System.out.println(funds.size());
	}

}
